//
//  ZCLiveViewController.m
//  ZCLive
//
//  Created by 彭军 on 2017/11/14.
//  Copyright © 2017年 Elvis. All rights reserved.
//

#import "ZCLiveViewController.h"
#import "UIAlertView_Block.h"
#import "ZLDefine.h"
#import <AVFoundation/AVFoundation.h>
#import <CCClassRoomBasic/CCClassRoomBasic.h>
#import "ZCAFURLRequestSerialization.h"
#import "ZCLiveBuildManager.h"
#import "ZCRoomInfoModel.h"
#import "ZCPreLiveViewController.h"
#import "ZCTipsView.h"
@interface ZCLiveViewController ()
@property(strong,nonatomic)UIView *innerView;
@property(strong,nonatomic)UIActivityIndicatorView *activityIndicatorView;
@property(nonatomic,strong)UIButton *closeBtn;
@property(nonatomic,strong)UIButton *flashBtn;
@property(nonatomic,strong)UIButton *screenBtn;
@property(nonatomic,strong)CCStreamView *streamView;
@property(nonatomic,strong)UILabel *tipsLbl;
@property(nonatomic,strong)UILabel *tipsFailedLbl;
@property(strong,nonatomic)NSURLSessionDataTask *sessionDataTask;
@property(assign,nonatomic)BOOL isStart;
@property(weak, nonatomic)NSTimer *timer;
@property(nonatomic,strong)NSNumber *isLogin;
@property(nonatomic,assign)BOOL isSubscribe;//是否订阅
@property(nonatomic,assign)BOOL isPushing;//是否已经推流
@property(nonatomic,assign)BOOL isStopSubscribeTimer;//当切到繁忙页面应该停止倒计时
@end

@implementation ZCLiveViewController

-(void)dealloc{
    NSLog(@"ZCLiveViewController dealloc");
   
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [UIApplication sharedApplication].idleTimerDisabled = YES;
    }
    return self;
}

-(void)startTimer{
    if (!self.timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

-(void)countDown{
    
    [_timer invalidate];
    _timer = nil;
    if (!self.isStart) {
        [self stopLive];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarOrientation = UIDeviceOrientationPortrait;
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    [[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceOrientationDidChangeNotification object:nil];
    [self removeObserver];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    [[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceOrientationDidChangeNotification object:nil];
    [UIApplication sharedApplication].statusBarOrientation = UIDeviceOrientationLandscapeRight;
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    [self addObserver];

    if (self.isStopSubscribeTimer) {
        self.isStopSubscribeTimer = NO;
    }else{
        __weak typeof(self) weakSelf = self;
        [self checkCameraAuthorization:^{
            if (weakSelf.isPreLive) {
                [weakSelf loginRoomAction];
            }else{
                [weakSelf loadData];
            }
        }];
    }
}


- (BOOL)shouldNavigateBack{
    
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    [[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceOrientationDidChangeNotification object:nil];
    [UIApplication sharedApplication].statusBarOrientation = UIDeviceOrientationLandscapeRight;
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];

    self.flashBtn.frame = CGRectMake(SCREEN_WIDTH - 26 - 14 , 14, 26, 34);
    [self.view addSubview: self.flashBtn];
    
    self.screenBtn.frame = CGRectMake(SCREEN_WIDTH - 14 - 64, (SCREENH_HEIGHT - 64)*0.5, 64, 64);
    [self.view addSubview:self.screenBtn];
    
    _innerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT)];
    _innerView.backgroundColor = [[UIColor alloc] initWithRed:0 green:0 blue:0 alpha:0.2];
    _innerView.hidden = YES;
    [self.view addSubview:_innerView];
    
    _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [_activityIndicatorView startAnimating];
    [_innerView addSubview:_activityIndicatorView];
    
    _activityIndicatorView.center = CGPointMake(SCREEN_WIDTH/2,SCREENH_HEIGHT/2);
    
    _tipsLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, _activityIndicatorView.frame.origin.y+50, SCREEN_WIDTH, 20)];
    _tipsLbl.text = @"视频连线中，请稍后...";
    _tipsLbl.textColor = [UIColor whiteColor];
    _tipsLbl.textAlignment = NSTextAlignmentCenter;
    _tipsLbl.font = [UIFont boldSystemFontOfSize:17];
    [_innerView addSubview:_tipsLbl];
    
    self.closeBtn.frame = CGRectMake(10, 20, 88, 44);
    [self.view addSubview:self.closeBtn];
    
    [CCStreamer setLogState:NO];
}

-(void)removeObserver{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CCNotiReceiveSocketEvent object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CCNotiNeedSubscriStream object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CCNotiNeedUnSubcriStream object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CCNotiNeedLoginOut object:nil];
}

-(void)addObserver{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveSocketEvent:) name:CCNotiReceiveSocketEvent object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(streamAdded:) name:CCNotiNeedSubscriStream object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(streamRemoved:) name:CCNotiNeedUnSubcriStream object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ccLoginOut:) name:CCNotiNeedLoginOut object:nil];
}


-(void)startSubscribeCountDown{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[CCStreamer sharedStreamer] updateUserCount];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       
        if (!self.isStopSubscribeTimer) {
            BOOL userCount = [CCStreamer sharedStreamer].getRoomInfo.room_user_count < 2;
            if (!self.isSubscribe && userCount) {
                [ZCTipsView showTips:@"坐席繁忙，请稍后再试！"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self gotoPreLiveVC:@"坐席繁忙，请稍后再试！"];
                });
                
            }else{
                self.isSubscribe = YES;
            }
        }
    });
}



-(void)ccLoginOut:(NSNotification *)noti{
    
    self.isLogin = @(NO);
    self.isDuanLiu = YES;
    //退出
    __weak typeof(self) weakSelf = self;
    [UIAlertView_Block initWithTitle:@"" message:@"网络太差，已断开" cancleButtonTitle:@"知道了" OtherButtonsArray:@[] clickAtIndex:^(NSInteger buttonIndex) {
        weakSelf.isPushing = NO;
        weakSelf.innerView.hidden = YES;
        [[CCStreamer sharedStreamer] leaveRoom:nil];
        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
        [weakSelf dismissViewControllerAnimated:YES completion:^{
            if (weakSelf.closeBlock) {
                weakSelf.closeBlock(YES, nil);
            }
        }];
    }];
}

- (void)streamAdded:(NSNotification *)noti
{
    self.isSubscribe = YES;
    NSLog(@"%s__%@", __func__, noti);
    NSString *streamID = noti.userInfo[@"streamID"];
    CCRole role = (CCRole)[noti.userInfo[@"role"] integerValue];
    __weak typeof(self) weakSelf = self;
    [[CCStreamer sharedStreamer] subcribeStream:streamID role:role qualityLevel:0 completion:^(BOOL result, NSError *error, id info){
        if (result)
        {
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionAllowBluetooth error:nil];
            [[AVAudioSession sharedInstance] setActive:YES error:nil];
            NSLog(@"%s__%@", __func__, info);
            if (role == CCRole_Student)
            {
               
            }
        }
        else
        {
            NSLog(@"%s__%d__sub stream error:%@", __func__, __LINE__, error);
            NSInteger code = error.code;
            if (code == 3001)
            {
                [UIAlertView_Block initWithTitle:@"注意" message:@"坐席订阅流失败是否重新订阅" cancleButtonTitle:@"否" OtherButtonsArray:@[@"是"]  clickAtIndex:^(NSInteger buttonIndex) {
                    if (buttonIndex == 1)
                    {
                        [weakSelf streamAdded:noti];
                    }
                }];
            }
        }
    }];
}

- (void)streamRemoved:(NSNotification *)noti
{
    NSString *streamID = noti.userInfo[@"streamID"];
    NSLog(@"%s__%@", __func__, noti);
    __weak typeof(self) weakSelf = self;
    [[CCStreamer sharedStreamer] unsubscribeStream:streamID completion:^(BOOL result, NSError *error, id info) {
        if (result) {
            NSLog(@"unsubcribe stream success");
        }
        else
        {
            NSLog(@"unsubcribe stream fail:%@", error);
        }
        [weakSelf stopLive];
    }];
}



- (void)checkCameraAuthorization:(void(^)())authorized{
    //IOS7以上版本验证是否开启摄像头权限
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
        //当未获取权限时 ios8以上可以直接跳转设置页面 以下只做提示
        if ([ [UIDevice currentDevice].systemVersion floatValue] < 8.0) {
            [UIAlertView_Block initWithTitle:@"相机访问权限未开启" message:@"要开启相机访问权限，您可以在\"设置-隐私-相机\"中开启" cancleButtonTitle:@"知道了" OtherButtonsArray:@[] clickAtIndex:nil];
        }else{
            
            [UIAlertView_Block initWithTitle:@"相机访问权限未开启" message:@"要开启相机访问权限，您可以点击“设置”，快速前往开启" cancleButtonTitle:@"知道了" OtherButtonsArray:@[@"设置"]  clickAtIndex:^(NSInteger buttonIndex) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
        }
    }else{
        if(authorized){
            authorized();
        }
    }
}


-(void)loadLivePreview{
    [[CCStreamer sharedStreamer] setCameraType:AVCaptureDevicePositionBack];
    __weak typeof(self) weakSelf = self;
    [[CCStreamer sharedStreamer] startPreview:^(BOOL result, NSError *error, id info) {
        CCStreamView *view = info;
        weakSelf.streamView = view;
        [weakSelf.view addSubview:view];
        [weakSelf.view sendSubviewToBack:view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf startPublish];
        });
        
    }];
}

#pragma mark - init 初始化获取坐席
-(void)loadData{
    _tipsLbl.text = @"正在寻找空闲坐席请稍后....";
    _innerView.hidden = NO;
    
    NSString *urlString = [NSString stringWithFormat:@"%@/remote/liveApply?phone=%@&licenseNo=%@",ZCHTTP,self.phoneNum,self.cartId];
    
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    __weak typeof(self) weakSelf = self;
    self.sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                
                [weakSelf successApply:data];
                
            }else{
                weakSelf.innerView.hidden = YES;
                [weakSelf failedApply:error];
            }
        });
        
    }];
    [self.sessionDataTask resume];
}

//获取坐席成功
-(void)successApply:(NSData *)data{
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    
    if (dict && dict.count) {
        
        NSString *code = [dict objectForKey:@"code"];
        NSString *msg = [dict objectForKey:@"msg"];
        NSDictionary *roomData = [dict objectForKey:@"data"];
        
        if ([code isEqualToString:@"0000"]) {
            
            self.roomInfo = [ZCRoomInfoModel yy_modelWithDictionary:roomData];
            [self loginRoomAction];
        }else {
            if (roomData) {
                self.roomInfo = [ZCRoomInfoModel yy_modelWithDictionary:roomData];
            }
            _innerView.hidden = YES;
            [self gotoPreLiveVC:msg];

        }
        
    }else{
        _innerView.hidden = YES;
    }
    
}

//获取坐席失败
-(void)failedApply:(NSError *)error{
    _innerView.hidden = YES;
    [self gotoPreLiveVC:@"您的网络不给力,请稍后再试！"];
}


-(void)gotoPreLiveVC:(NSString *)msg{
    self.isStopSubscribeTimer = YES;
    if (self.isPushing) {
        _innerView.hidden = NO;
        _tipsLbl.text = @"坐席繁忙，请稍后...";
        __weak typeof(self) weakSelf = self;
        [self clearLiveData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.innerView.hidden = YES;
            [weakSelf jumpToPreVC];
        });
    }else{
        [[CCStreamer sharedStreamer] leaveRoom:nil];
        [self jumpToPreVC];
    }
    
}

-(void)jumpToPreVC{
    _innerView.hidden = YES;
#ifdef TEST_ZC
    ZCPreLiveViewController *preLiveVC = [[ZCPreLiveViewController alloc] init];
#else
    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"ZCLiveSDKBundle" withExtension:@"bundle"]];
    ZCPreLiveViewController *preLiveVC = [[ZCPreLiveViewController alloc] initWithNibName:@"ZCPreLiveViewController" bundle:bundle];
#endif
    preLiveVC.cartId = self.cartId;
    preLiveVC.phoneNum = self.phoneNum;
    preLiveVC.roomInfo = self.roomInfo;
    __weak typeof(self) weakSelf = self;
    preLiveVC.closeBlock = ^(BOOL success, NSString *info) {
        if (weakSelf.closeBlock) {
            weakSelf.closeBlock(success, info);
        }
    };
    [self.navigationController pushViewController:preLiveVC animated:YES];
}

#pragma mark - 登录房间
-(void)loginRoomAction{
//#ifdef TEST_ZC
//    self.roomInfo = [[ZCRoomInfoModel alloc] init];
//    self.roomInfo.roomId = @"CAD37878607B56919C33DC5901307461";
//    self.roomInfo.roomName = @"12132131";
//    self.roomInfo.userId = @"F08A8B432F24065A";
//    self.roomInfo.passWord = @"123456";
//#endif
    if (!self.roomInfo && !self.roomInfo.roomId) {
        return;
    }
    
    [[CCStreamer sharedStreamer] stopPreview];
    
    _tipsLbl.text = @"视频连线中，请稍后...";
    _innerView.hidden = NO;

    CCEncodeConfig *config = [[CCEncodeConfig alloc] init];
    config.fps = 24;
    
    CCResolution videoSize;
    if ([ZCLiveBuildManager sharedInstance].resolution==ZCResolution_LOW) {
        videoSize = CCResolution_LOW;
    }else{
        videoSize = CCResolution_HIGH;
    }
    config.reslution = videoSize;
    
    __weak typeof(self) weakSelf = self;
    [[CCStreamer sharedStreamer] loginWithRoomID:self.roomInfo.roomId userID:self.roomInfo.userId role:CCRole_Teacher password:self.roomInfo.passWord nickName:self.roomInfo.roomName config:config isLandSpace:YES completion:^(BOOL result, NSError *error, id info) {
        
        if (result)
        {
            [[CCStreamer sharedStreamer] joinRoom:^(BOOL result, NSError *error, id info) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (result)
                    {
                        [weakSelf streamLoginSuccess:info];
                    }
                    else
                    {
                        [weakSelf streamLoginFail:error];
                    }
                });
            }];
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf streamLoginFail:error];
            });
        }
    }];
    
}

- (void)streamLoginSuccess:(NSDictionary *)info
{
    _innerView.hidden = YES;
    self.isLogin = @(YES);
    [self loadLivePreview];
}

- (void)streamLoginFail:(NSError *)error
{
    self.isLogin = @(NO);
    _innerView.hidden = YES;
    [ZCTipsView showTips:@"坐席繁忙，请稍后..."];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self gotoPreLiveVC:@"坐席繁忙，请稍后..."];
    });
}

- (void)receiveSocketEvent:(NSNotification *)noti
{
    CCSocketEvent event = [noti.userInfo[@"event"] integerValue];
    id value = noti.userInfo[@"value"];
    if (event == CCSocketEvent_Chat)
    {
        //聊天信息
        [self chat_message:value];
    }
    else if (event == CCSocketEvent_StreamRemoved)
    {
        [self stopLive];
    }else if (event == CCSocketEvent_UserListUpdate)
    {
        NSInteger str = [[CCStreamer sharedStreamer] getRoomInfo].room_user_count;
        NSString *userCount = [NSString stringWithFormat:@"%ld个成员", (long)str];
        NSLog(@"-----目前房间人数： %@",userCount);
        if (userCount.integerValue>=2) {
            self.isSubscribe = YES;
        }else{
            if (self.isSubscribe && userCount.integerValue < 2) {
                [ZCTipsView showTips:@"坐席已退出！"];
                [self stopLive];
            }
        }
        
    }else if(event == CCSocketEvent_SocketReconnecting){
        
        
    }else if (event == CCSocketEvent_SocketReconnected){
    
        
    }else if (event == CCSocketEvent_LianmaiStateUpdate){
        [[CCStreamer sharedStreamer] updateUserCount];
    }
}

- (void)chat_message:(NSDictionary *)dic
{
    NSString *msg = dic[@"msg"];
    
    if ([msg isKindOfClass:[NSString class]])
    {
        if ([msg rangeOfString:@"photo"].location !=NSNotFound) {
            [self screenBtnClicked];
        }else if ([msg rangeOfString:@"light"].location !=NSNotFound){
            [self flashBtnClicked:self.flashBtn];
        }else if ([msg rangeOfString:@"stopLive"].location !=NSNotFound){
            [self stopLive];
        }
        
    }
    
}

#pragma mark - init 初始化获取坐席
-(void)liveStart{
    NSString *urlString = [NSString stringWithFormat:@"%@/remote/liveStart?webUserName=%@&webUserId=%@&ccRoomid=%@&ccPassWord=%@",ZCHTTP,self.roomInfo.webUserName,self.roomInfo.webUserId,self.roomInfo.roomId,self.roomInfo.passWord];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    __weak typeof(self) weakSelf = self;
    self.sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                
                [weakSelf successliveStart:data];
                
            }else{
                weakSelf.innerView.hidden = YES;
                [weakSelf failedliveStart:error];
            }
        });
        
    }];
    [self.sessionDataTask resume];
}

-(void)successliveStart:(NSData *)data{

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    
    if (dict && dict.count) {
        
        NSString *code = [dict objectForKey:@"code"];
        if ([code isEqualToString:@"0000"]) {
            
            [self startSubscribeCountDown];
            
        }else {
            [self gotoPreLiveVC:nil];
        }
        
    }else{
        
        [self gotoPreLiveVC:nil];
    }

}

-(void)failedliveStart:(NSError *)error{
    
    [self gotoPreLiveVC:nil];
    
}



#pragma mark 开始推流
- (void)startPublish
{
    //开始推流
    _innerView.hidden = NO;
    NSLog(@"%s", __func__);
    
    CCLiveStatus status = [[CCStreamer sharedStreamer] getRoomInfo].live_status;
    __weak typeof(self) weakSelf = self;
    if (status == CCLiveStatus_Stop)
    {
        
        [self startTimer];
        //直接调用publish
        BOOL result =  [[CCStreamer sharedStreamer] startPublish:^(BOOL result, NSError *error, id info) {
            
            if (result)
            {
                NSLog(@"%s", __func__);
                [weakSelf setRtmpUrl];
                weakSelf.isStart = YES;
                [weakSelf liveStart];
            }
            else
            {
                NSLog(@"publish error:%@", error);
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //调整btn显示隐藏
                weakSelf.innerView.hidden = YES;
            });
        }];
        
        if (!result) {
            self.innerView.hidden = YES;
        }
    }
    else
    {
        [UIAlertView_Block initWithTitle:@"注意" message:@"是否继续上场直播" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"继续"]  clickAtIndex:^(NSInteger buttonIndex) {
            if (buttonIndex == 0)
            {
                //不继续，需要停止上场直播
                NSLog(@"%s__%d", __func__, __LINE__);
                [[CCStreamer sharedStreamer] stopLive:^(BOOL result, NSError *error, id info) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (result)
                        {
                            [weakSelf startTimer];
                            [[CCStreamer sharedStreamer] startPublish:^(BOOL result, NSError *error, id info) {
                                if (result)
                                {
                                    NSLog(@"%s", __func__);
                                    [weakSelf setRtmpUrl];
                                    weakSelf.isStart = YES;
                                    [weakSelf liveStart];
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        //调整btn显示隐藏
                                        weakSelf.innerView.hidden = YES;
                                    });
                                    
                                    
                                }
                                else
                                {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        weakSelf.innerView.hidden = YES;
                                    });
                                    NSLog(@"publish error:%@", error);
                                }
                            }];
                        }
                        else
                        {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                weakSelf.innerView.hidden = YES;
                            });
                            NSLog(@"stop live error:%@", error);
                        }
                    });
                }];
            }
            else
            {
                [weakSelf startTimer];
                [[CCStreamer sharedStreamer] startPublish:^(BOOL result, NSError *error, id info) {
                    if (result)
                    {
                        NSLog(@"%s", __func__);
                        [weakSelf setRtmpUrl];
                        weakSelf.isStart = YES;
                        [weakSelf liveStart];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //调整btn显示隐藏
                            weakSelf.innerView.hidden = YES;
                            
                        });
                        /*异常退出之后，再次登录，要拉取处于推流中坐席的流*/
                        if ([[CCStreamer sharedStreamer] getRoomInfo].live_status == CCLiveStatus_Start)
                        {
                            //这个时候订阅所有的流
                            NSArray *allStreamIDS = [[CCStreamer sharedStreamer] getAllEnableSubStreamIDs];
                            for (NSDictionary *info in allStreamIDS)
                            {
                                NSNotification *noti = [[NSNotification alloc] initWithName:CCNotiNeedSubscriStream object:nil userInfo:info];
                                [weakSelf streamAdded:noti];
                            }
                        }
                    }
                    else
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            weakSelf.innerView.hidden = YES;
                        });
                        NSLog(@"publish error:%@", error);
                    }
                }];
            }
        }];
    }
}

#pragma mark - rtmp
- (void)setRtmpUrl
{
    self.isPushing = YES;
    NSString *url = [[CCStreamer sharedStreamer] getRoomInfo].rtmpUrl;
    NSLog(@"url%@", url);
    [[CCStreamer sharedStreamer] addExternalOutput:url completion:^(BOOL result, NSError *error, id info) {
        NSLog(@"%s__%@__%@__%@", __func__, @(result), error, info);
    }];
}

- (void)removeRtmpUrl
{
    self.isPushing = NO;
    NSString *url = [[CCStreamer sharedStreamer] getRoomInfo].rtmpUrl;
    NSLog(@"url%@", url);
    [[CCStreamer sharedStreamer] removeExternalOutput:url completion:^(BOOL result, NSError *error, id info) {
        NSLog(@"%s__%@__%@__%@", __func__, @(result), error, info);
        
    }];
}


-(void)closeBtnClicked
{
    NSString *message = @"确认退出吗？";
    __weak typeof(self) weakSelf = self;
    [UIAlertView_Block initWithTitle:@"" message:message cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex) {
        if (buttonIndex == 1)
        {
            [UIApplication sharedApplication].idleTimerDisabled = NO;
            [weakSelf stopLive];
        }
    }];
}

#pragma mark - 关闭直播数据
-(void)stopLive{
    self.isStopSubscribeTimer = YES;
    if (self.isPushing) {
        self.tipsLbl.text = @"正在退出，请稍后...";
        self.innerView.hidden = NO;

        __weak typeof(self) weakSelf = self;
        
        [self clearLiveData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
            weakSelf.isPushing = NO;
            weakSelf.innerView.hidden = YES;
            [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                if (weakSelf.closeBlock) {
                    weakSelf.closeBlock(YES, nil);
                }
            }];

        });

    }else{

        [[CCStreamer sharedStreamer] leaveRoom:nil];
        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
         __weak typeof(self) weakSelf = self;
        [self dismissViewControllerAnimated:YES completion:^{
            if (weakSelf.closeBlock) {
                weakSelf.closeBlock(YES, nil);
            }
        }];

    }
    
    
}


-(void)clearLiveData{
    [[CCStreamer sharedStreamer] stopPublish:^(BOOL result, NSError *error, id info) {
        if (result)
        {
            [self removeRtmpUrl];
            [[CCStreamer sharedStreamer] leaveRoom:nil];
            
        }
    }];
}



-(void)flashBtnClicked:(UIButton *)sender{
    
    sender.selected = !sender.selected;
    if (sender.isSelected == YES) { //打开闪光灯
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        NSError *error = nil;
        
        if ([captureDevice hasTorch]) {
            BOOL locked = [captureDevice lockForConfiguration:&error];
            if (locked) {
                captureDevice.torchMode = AVCaptureTorchModeOn;
                [captureDevice unlockForConfiguration];
            }
        }
    }else{//关闭闪光灯
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            [device setTorchMode: AVCaptureTorchModeOff];
            [device unlockForConfiguration];
        }
    }
    
}

-(void)screenBtnClicked{
    
    UIImage *image = [self.streamView snapshot];
    [self uploadImg:image];
}


-(void)uploadImg:(UIImage *)image{
    _innerView.hidden = NO;
    _tipsLbl.text = @"正在上传图片，请稍后...";
    NSString *longitude= [ZCLiveBuildManager sharedInstance].longitude.stringValue;
    NSString *latitude=  [ZCLiveBuildManager sharedInstance].latitude.stringValue;
    NSString *timeInterval = [NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]*1000];
    NSString *survey_id = self.roomInfo.surveyId;
    NSString *urlString = [NSString stringWithFormat:@"%@/remote/uploadImage?longitude=%@&latitude=%@&surveyId=%@&time=%@",ZCHTTP,longitude,latitude,survey_id,timeInterval];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSError *serializationError = nil;
    ZCAFHTTPRequestSerializer *serializer = [[ZCAFHTTPRequestSerializer alloc] init];
    __weak typeof(self) weakSelf = self;
    NSMutableURLRequest * formRequest = [serializer multipartFormRequestWithMethod:@"POST" URLString:url.absoluteString parameters:nil constructingBodyWithBlock:^(id<ZCAFMultipartFormData>  _Nonnull formData) {
        [weakSelf addImage:image toFormData:formData];
    } error:&serializationError];
    
    self.sessionDataTask = [session dataTaskWithRequest:formRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.innerView.hidden = YES;
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200) {
                [weakSelf success:data];
            }else{
                [ZCTipsView showTips:@"上传失败,请重试！"];
            }
        });
    }];
    [self.sessionDataTask resume];
}

-(void)success:(NSData *)data{
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
    if (dict.count) {
        NSString *code = [dict objectForKey:@"code"];
        NSString *msg = [dict objectForKey:@"msg"];
        if ([code isEqualToString:@"0000"]) {
             [ZCTipsView showTips:@"上传图片成功"];
        }else{

            [ZCTipsView showTips:msg];
        }
        
    }else{
        [ZCTipsView showTips:@"上传失败,请重试！"];
    }
    
}


- (void)addImage:(UIImage *)image toFormData:(id<ZCAFMultipartFormData>)formData{
    NSData *imageData = UIImageJPEGRepresentation(image, 0.6);
    NSString *fileName = @"file.png";
    NSString *name = @"file";
    [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/png"];
}


-(UIButton *)closeBtn
{
    if(!_closeBtn)
    {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_closeBtn setImage:[UIImage imageNamed:KZCBundleImg(@"zc_live_back")] forState:UIControlStateNormal];
        [_closeBtn setTitle:@"返回" forState:UIControlStateNormal];
        [_closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(closeBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

-(UIButton *)flashBtn
{
    if(!_flashBtn)
    {
        _flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_flashBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_flashBtn setImage:[UIImage imageNamed:KZCBundleImg(@"zc_flash")] forState:UIControlStateNormal];
        [_flashBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_flashBtn addTarget:self action:@selector(flashBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _flashBtn;
}


-(UIButton *)screenBtn
{
    if(!_screenBtn)
    {
        _screenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_screenBtn.imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_screenBtn setImage:[UIImage imageNamed:KZCBundleImg(@"zc_play")] forState:UIControlStateNormal];
        [_screenBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_screenBtn addTarget:self action:@selector(screenBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _screenBtn;
}



- (void)interfaceOrientation:(UIInterfaceOrientation)orientation
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector             = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val                  = orientation;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}


-(BOOL)shouldAutorotate{
    
    return YES;
    
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskLandscapeRight;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

